﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using CSF.WebApp.Admin.Models;
using CSF.Service.Accounts.Client;
using CSF.Security.Data;
using CSF.Utility.Mvc;
using CSF.Customers.Data;
using System.ServiceModel;
using CSF.BusinessCore.Service;

namespace CSF.WebApp.Admin.Controllers
{
    public class AccountController : SecureController
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        public ActionResult LogOn(string returnUrl)
        {

            return View();           
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                string ipAddress = Request.UserHostAddress;
                string httpForwarded = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                string appCode = AccountServiceConfigManager.Load().AppCode;
                ApplicationSvcClient appSvc = new ApplicationSvcClient();
                Application application = appSvc.GetOneByCode(appCode);
                AuthenticateSvcClient svc = new AuthenticateSvcClient();
                string sessionId = svc.LogOn(model.UserName, model.Password,
                    application.Id, ipAddress, httpForwarded);
                if (sessionId != null)
                {
                    returnUrl = UrlUtility.AppendParameter(returnUrl, "SessionId", sessionId);
                    return Redirect(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
            return View(model);
        }

        public ActionResult Register()
        {
            RegisterViewData();
            return View();
        }

        [HttpPost]
        public ActionResult Register(Models.RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                //UserAccount account = new UserAccount();
                //account.UserName = model.Email;
                //account.Email = model.Email;
                //account.IsStaff = false;
                //account.Password = model.Password;
                //account.FirstName = model.FirstName;
                //account.LastName = model.LastName;
                //account.CreateBy = account.UserName;

                //account.IsApproved = true;
                //account.ApproveBy = account.UserName;
                //account.ApproveTime = DateTime.Now;

                //Customer customer = new Customer();
                //customer.NickName = model.FirstName;
                //customer.FullName = model.FirstName + " " + model.LastName;
                //customer.Email = model.Email;
                //customer.InMailList = model.InMailList;
                //customer.CountryCode = model.CountryCode;
                //customer.ApproveStatus = ApprovalStatus.Waiting;
                //customer.CreateBy = account.UserName;

                //try
                //{
                //    CustomerSvcClient svc = new CustomerSvcClient();
                //    int id = svc.RegisterWithUser(account, customer, _application.Id);

                //    AuthenticateSvcClient authsvc = new AuthenticateSvcClient();
                //    string ipAddress = Request.UserHostAddress;
                //    string httpForwarded = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                //    string sessionId = authsvc.LogOn(account.UserName, account.Password, _application.Id, ipAddress, httpForwarded);
                //    if (!string.IsNullOrEmpty(sessionId))
                //    {
                //        _toUrl = UrlUtility.AppendParameter(_toUrl, "SessionId=", sessionId);
                //        return RedirectToAction("MyDetail", "Customer", new { SessionId = sessionId, toUrl = _toUrl });
                //    }
                //    else
                //        return Redirect(_toUrl);
                //}
                //catch (FaultException<ExceptionWrapper<DuplicateUserNameException>>)
                //{
                //    ModelState.AddModelError("Email", "Email is registered by another user.");
                //}
                //catch (FaultException ex)
                //{
                //    ModelState.AddModelError("", ex);
                //}
            }
            RegisterViewData();
            return View(model);
        }

        [NonAction]
        private void RegisterViewData()
        {
            CountrySvcClient svc = new CountrySvcClient();

            var qcountry = from p in svc.GetEnable()
                           orderby p.Name1
                           select new SelectListItem { Value = p.Code, Text = p.Name1 };
            ViewBag.CountryList = qcountry.AsEnumerable();
        }

        //[Authorize]
        //public ActionResult MyAccount()
        //{
        //    UserAccountSvcClient svc = new UserAccountSvcClient();
        //    UserAccount userAccount = svc.GetOneById(_userSession.UserId);

        //    return View(userAccount);
        //}

        //[Authorize]
        //[HttpPost]
        //public ActionResult MyAccount(UserAccount userAccount)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        UserAccountSvcClient svc = new UserAccountSvcClient();

        //        svc.UpdateBySelf(userAccount);

        //        return Redirect(_toUrl);
        //    }
        //    return View(userAccount);
        //}

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //[Authorize]
        //[HttpPost]
        //public ActionResult ChangePassword(ChangePasswordModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        UserAccountSvcClient svc = new UserAccountSvcClient();
        //        if (svc.ChangePassword(_userSession.UserId, model.OldPassword, model.NewPassword, User.Identity.Name))
        //        {
        //            return Redirect(_toUrl);
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
        //        }
        //    }

        //    // 如果我们进行到这一步时某个地方出错，则重新显示表单
        //    return View(model);
        //}

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff(string SessionId)
        {
            //FormsService.SignOut();
            if (!string.IsNullOrEmpty(SessionId))
            {
                HttpContext.Cache.Remove(SessionId);
                HttpContext.User = new GenericPrincipal(new GenericIdentity(""), null);
                AuthenticateSvcClient svc = new AuthenticateSvcClient();
                svc.LogOff(SessionId);
            }

            return RedirectToAction("Index", "Home");
        }
    }
}
